<?php
class Answer_Service_Point extends Phpfox_Service {
    function __construct()
    {
        $this->_sTable = Phpfox::getT('brodev_answer_point');
        $this->_sTableUser = Phpfox::getT('user');
    }
    /**
     * get categories from database without page
     * @param string $sFields
     * @param array $aConditions
     * @param string $sOrder
     * @param int $iLimit
     * @return array
     */
    public function getListNoPage($sFields = '*', $aConditions = array(), $sOrder = 'created') {
        $aRecords = $this->database()
            ->select($sFields)
            ->from($this->_sTable, 'p')
            ->where($this->getCondition($aConditions))
            ->order($sOrder)
            ->execute('getRows')
        ;
        return array(
            'data' => $aRecords
        );
    }
    /**
     * get total point from user
     * @param int $iUserId
     * @return int
     */
    public function getPoint($iUserId) {
            $point = 0;
            $aPoints = $this->database()
                ->select('action')
                ->from($this->_sTable, 'p')
                ->where('p.user_id = '.$iUserId)
                ->execute('getRows');
            foreach ($aPoints AS $aItem) {
                $point += $this->setPoint($aItem['action']);
            }
            $aRow = $this->database()->select("ua.activity_answers, ua.activity_total, ua.activity_points, u.user_group_id")
                ->from(Phpfox::getT('user_activity'), 'ua')
                ->join(Phpfox::getT('user'), 'u', 'u.user_id = ua.user_id')
                ->where('ua.user_id = ' . (int) $iUserId)
                ->execute('getRow');
            $iPointCal = $point - $aRow['activity_answers'];
            $aUpdate = array(
                'activity_answers' => $point,
                'activity_total' => $aRow['activity_total'] + $iPointCal,
                'activity_points' => $aRow['activity_points'] + $iPointCal
            );
            $this->database()->update(Phpfox::getT('user_activity'), $aUpdate, 'user_id = '. $iUserId);
            $iPoint = $point;

        return $iPoint;
    }
    /**
     * insert or update category to database
     * @param $aVal
     * @param $iId
     * @return bool
     */
    public function saveDatabase($aVal) {
        if ( $this->isExist($aVal) ==0 ) {
            $iId = $this->database()
                ->insert($this->_sTable, $aVal)
            ;
            if (!$iId)
            {
                return false;
            }
            else {
                Phpfox::getService('answer.level')->changeLabel($aVal['user_id']);
                return true;
            }
        }
        else {

            return $this->database()->update($this->_sTable, $aVal, "id = " . $this->isExist($aVal));
        }
    }

    /**
     * set Point from action
     * 1: Ask a question
     * 2: Answer a question
     * 3: Vote a question
     * 4: Answer correct
     * @param int $iAction
     * @return int mixed
     */
    public function setPoint($iAction) {
        switch ($iAction) {
            case 1: return Phpfox::getParam('answer.ask_a_question');
            break;
            case 2: return Phpfox::getParam('answer.answer_question');
            break;
            case 3: return Phpfox::getParam('answer.vote_answer');
            break;
            case 4: return Phpfox::getParam('answer.answer_correct');
            break;
        }
    }

    /**
     * get point and label from one user
     * @param int $iUserId
     * @return array
     */
    public function getUser ($iUserId) {
        $aUser = $this->database()
            ->select(Phpfox::getUserField())
            ->from($this->_sTableUser, 'u')
            ->where('u.user_id = '. $iUserId)
            ->execute('getRow');
        $aUser['point'] = $this->getPoint($iUserId);
        $aUser['label'] = Phpfox::getService('answer.level')->getLabel($iUserId);
        return $aUser;
    }
	
	function getScores(){
		$sOrder = 'm.point DESC';
		$result = $this->database()->select('m.*, u.*')
				->from(Phpfox::getT('brodev_answer_userpoint'), 'm')
				->join(Phpfox::getT('user'), 'u', 'u.user_id = m.userid')
				->where('m.point > 0')
				->order($sOrder)
				->execute('getRows');
		return $result;
	}
    /**
     * get all user
     * @param int $iPage
     * @param int $iLimit
     * @return array
     */
    public function getMember($iPage = 1, $iLimit = 20) {
        $iCount = $this->database()
            ->select('COUNT(*)')
            ->from($this->_sTableUser,'u')
            ->execute('getField');
        $aUser = $this->database()
            ->select(Phpfox::getUserField())
            ->from($this->_sTableUser, 'u')
            ->execute('getRows');
        foreach ($aUser as $iKey => $val) {
            $aUser[$iKey]['point'] = $this->getPoint($val['user_id']);
            $aUser[$iKey]['label'] = Phpfox::getService('answer.level')->getLabel($val['user_id']);
            if (Phpfox::getUserId() != $val['user_id']) {
                $aUser[$iKey]['isFriend'] = Phpfox::getService('friend.friend')->isFriend(Phpfox::getUserId(),$val['user_id']);
            }
            else {
                $aUser[$iKey]['isFriend'] = true;
            }
            $aCount = $this->getUserInfo($val['user_id']);
            $aUser[$iKey]['ask'] = $aCount['ask'];
            $aUser[$iKey]['answer'] = $aCount['answer'];
        }
        $aUser = $this->subval_sort($aUser,'point');
        $iBegin = ($iPage - 1)*$iLimit;
        $iEnd = ($iPage)* $iLimit;
        if ($iEnd > $iCount) {
            $iEnd = $iCount;
        }
        for ($i = $iBegin; $i < $iEnd; $i++ ) {
            $aData[]=$aUser[$i];
        }
        return array(
            'data' => $aData,
            'count' => $iCount
        );
    }

    /**
     * get correct answer id
     * @param int $iQuestionId
     * @return int
     */
    public function getCorrectAnswer($iQuestionId = 0) {
        if ($iQuestionId ==0 ) {
            return 0;
        }
        $aRecord = $this->database()
            ->select('answer_id')
            ->from($this->_sTable)
            ->where('action = 4 and question_id ='. $iQuestionId)
            ->execute('getField');
        return (int) $aRecord;
    }
    /**
     * chose correct answer
     * @param $iQuestionId
     * @param $iAnswerId
     * @return Question id
     */
    public function correct($iAnswerId) {
        $aCondition = 'a.id = '. $iAnswerId;
        $aAnswer = Phpfox::getService('answer.answer')->getForEdit($aCondition);
        $aAnswer = $aAnswer['data'];
        $aVal = array(
            'question_id' => $aAnswer['question_id'],
            'answer_id' => $iAnswerId,
            'user_id' => $aAnswer['user_id'],
            'action' => 4
        );
        $aCondition = array(
            'question_id ='. $aAnswer['question_id'],
            'action =4'
        );
        $aRecords = $this->getListNoPage('*',$aCondition);
        foreach ($aRecords['data'] as $aItem) {
            $this->delete($aItem['id']);
        }
        $this->saveDatabase($aVal);
        Phpfox::getService('feed.process')->add('answer_correct', $iAnswerId);

        return $aAnswer['question_id'];
    }
    /**
     * remove correct answer
     * @param $iQuestionId
     * @param $iAnswerId
     * @return Question id
     */
    public function uncorrect($iAnswerId) {
        $aCondition = array('a.id = '. $iAnswerId);
        $aAnswer = Phpfox::getService('answer.answer')->getForEdit($aCondition);
        $aAnswer = $aAnswer['data'];
        $aCondition = array(
            'question_id ='. $aAnswer['question_id'],
            'action =4'
        );
        $aRecords = $this->getListNoPage('*',$aCondition);
        foreach ($aRecords['data'] as $aItem) {
            $this->delete($aItem['id']);
        }
        return $aAnswer['question_id'];
    }
    /**
     * sort array by key
     * @param $aArray
     * @param $sKey
     * @return array
     */
    function subval_sort($aArray,$sKey) {
        foreach($aArray as $k=>$v) {
            $aTemp[$k] = strtolower($v[$sKey]);
        }
        arsort($aTemp);
        foreach($aTemp as $key=>$val) {
            $aResult[] = $aArray[$key];
        }
        return $aResult;
    }
    /**
     * Check Exist
     * @param array $aCondition
     * @return bool
     */
    /**
     * convert array to condition string
     * @param array $aCondition
     * @return string
     *
     */
    private function getCondition( $aCondition ) {
        $sCondition = "1=1";
        foreach ($aCondition AS $Array) {
            $sCondition .= " AND ". $Array;
        }
        return $sCondition;
    }

    /**
     * Check Exist if yes return id
     * @param array $aConditions
     * @return int
     */
    public function isExist($aConditions) {
        if ($aConditions['answer_id']==0) {
            return 0;
        }
        $aCondition = array(
            'user_id = '. $aConditions['user_id'],
            'action = '. $aConditions['action'],
            'answer_id ='. $aConditions['answer_id']
        );
        $iId = $this->database()
            ->select('id')
            ->from($this->_sTable)
            ->where($this->getCondition($aCondition))
            ->execute('getField');
        return (int) $iId;
    }

    /**
     * get count vote up and vote down from answer
     * @param int $iAnswer
     * @return array
     */
    public function getVote($iAnswer) {
        $iUp = $this->database()
            ->select('count(*)')
            ->from($this->_sTable)
            ->where('action = 3 and up = 1 and  answer_id = '. $iAnswer)
            ->execute('getField');
        $iDown = $this->database()
            ->select('count(*)')
            ->from($this->_sTable)
            ->where('action = 3 and up = 0 and answer_id = '. $iAnswer)
            ->execute('getField');
        $iCheckVoteDown = $this->database()
            ->select('count(*)')
            ->from($this->_sTable)
            ->where('action = 3 and up = 0 and answer_id = '. $iAnswer .' and user_id = '. Phpfox::getUserId())
            ->execute('getField');
        $iCheckVoteUp = $this->database()
            ->select('count(*)')
            ->from($this->_sTable)
            ->where('action = 3 and up = 1 and answer_id = '. $iAnswer .' and user_id = '. Phpfox::getUserId())
            ->execute('getField');
        return array(
            'voteUp' => $iUp,
            'voteDown' => $iDown,
            'checkVoteUp' => $iCheckVoteUp,
            'checkVoteDown' => $iCheckVoteDown,
        );
    }
    /**
     * delete category from database      *
     * @param $iId
     * @return bool
     */
    public function delete($iId) {
        $iUserId = $this->database()
            ->select('user_id')
            ->from($this->_sTable)
            ->where('id = '. $iId)
            ->execute('getField');

        $this->database()->delete($this->_sTable, 'id = ' . $iId);
        Phpfox::getService('answer.level')->changeLabel($iUserId);
        return true;
    }
    public function getUserInfo ($iUserId) {
        $iAskQuestion = $this->database()
            ->select('count(*) as total_ask')
            ->from($this->_sTable)
            ->where('action = 1 and user_id ='. $iUserId)
            ->execute('getField');
        $iAnswer = $this->database()
            ->select('count(*) as total_answer')
            ->from($this->_sTable)
            ->where('action = 2 and user_id ='. $iUserId)
            ->execute('getField');
        return array (
            'ask' => $iAskQuestion,
            'answer' => $iAnswer
        );
    }
}